//
//  ReferencePriceViewController.m
//  
//
//  Created by ツナミ 龍 on 15/12/16.
//
//

#import "ReferencePriceViewController.h"
#import "PriceViewModel.h"
#import "AppDelegate.h"

#define BIND_LABEL(v, k, l, s) [RACObserve(v, k) subscribeNext:^(NSString *msg) {  \
        @strongify(s);   \
        s.l.text = msg;  \
        s.l.hidden = NO; \
}]

@interface ReferencePriceViewController ()

@property (weak, nonatomic) IBOutlet UILabel *message1Label;
@property (weak, nonatomic) IBOutlet UILabel *message2Label;
@property (weak, nonatomic) IBOutlet UILabel *message3Label;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;

@end

@implementation ReferencePriceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self bindViewModel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)bindViewModel {
    if (self.message1Label.hidden == NO) {
        return;
    }
    PriceViewModel *viewModel = [PriceViewModel sharedInstance];
    @weakify(self);
    
    BIND_LABEL(viewModel, message1String, message1Label, self);
    BIND_LABEL(viewModel, message2String, message2Label, self);
    BIND_LABEL(viewModel, message3String, message3Label, self);
    
    AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [delegate.indicatorDispose dispose];
    
    delegate.indicatorDispose = [viewModel.executeSend.executing subscribeNext:^(NSNumber *x) {
        @strongify(self);
        BOOL executing = [x boolValue];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = executing;
        self.loadingIndicator.hidden = !executing;
        if (executing) {
            [self.loadingIndicator startAnimating];
        } else {
            [self.loadingIndicator stopAnimating];
        }
    }];
    
    [viewModel.connectionErrors subscribeNext:^(NSError *error) {
//        viewModel.apiSucceed = YES; // for debug
        if (viewModel.apiSucceed) {
            return ;
        }
        NSError *err = nil;
        NSString *errMsg = nil;
        NSData *jsonData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        if (jsonData) {
            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                       options:NSJSONReadingAllowFragments
                                                                         error:&err];
            
            DDLog(@"%@", jsonObject);
            errMsg = jsonObject[@"error"];
        } else {
            errMsg = error.userInfo[NSLocalizedDescriptionKey];
        }
        
        if (errMsg == nil) {
            errMsg = @"サーバー通信に失敗しました";
        }
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:@"Error"
                                   message:errMsg
                                  delegate:nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
    }];
    
    [viewModel.executeSend execute:nil];
}

#pragma mark - IBAction

- (IBAction)terminate:(id)sender
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
}

@end
